const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken, encryptPhone, decryptPhone, getNextId, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');

router.get('/', authenticateToken, async (req, res) => {
    try {
        const { emp_name } = req.query;
        let sql = `SELECT employee.*, position.position_name, department.dept_name FROM employee INNER JOIN position ON employee.position_id = position.position_id INNER JOIN department ON position.dept_id = department.dept_id`;
        if (emp_name) {
            sql += ` WHERE employee.emp_name LIKE '%${emp_name}%'`;
        }
        let [result] = await db.execute(sql);
        result.forEach(item => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss');
            item.phone = decryptPhone(item.phone).replace(/^(\d{3})\d+(\d{4})$/, '$1****$2');
            item.hire_date = dayjs(item.hire_date).format('YYYY-MM-DD');
        });
        await logUserOperation(req, '查询', '获取员工列表', '获取员工列表成功', '成功');
        res.json({
            success: true,
            message: '获取员工列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取员工列表失败:', error);
        await logUserOperation(req, '查询', '获取员工列表', '获取员工列表失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取员工列表失败',
            error: error.message
        });
    }
});

// 获取部门列表 
router.get('/getDepartment', authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT dept_id as 'key', dept_name as 'name' FROM department`;
        let [result] = await db.execute(sql);
        await logUserOperation(req, '查询', '获取部门列表', '获取部门列表成功', '成功');
        res.json({
            success: true,
            message: '获取部门列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取部门列表失败:', error);
        await logUserOperation(req, '查询', '获取部门列表', '获取部门列表失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取部门列表失败',
            error: error.message
        });
    }
});

// 获取岗位列表
router.get('/getPosition', authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT position_id as 'key', position_name as 'name' FROM position`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取岗位列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取岗位列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取岗位列表失败',
            error: error.message
        });
    }
});

// 在职状态 在职/休假/离职
router.get('/getEmployeeStatus', authenticateToken, async (req, res) => {
    res.json({
        success: true,
        message: '获取在职状态成功',
        data: [
            { key: '在职', name: '在职' },
            { key: '休假', name: '休假' },
            { key: '离职', name: '离职' }
        ]
    });
});

// 添加员工
// 参数:{ "emp_name": "黄", "gender": "男", "dept_id": "A001", "position_id": "P001", "hire_date": "2025-07-11", "phone": "15302254544", "status": "在职", "notes": "备注一下" }
router.put('/add', authenticateToken, async (req, res) => {
    try {
        const { emp_name, gender, dept_id, position_id, hire_date, phone, status, notes } = req.body;
        const emp_id = await getNextId('MG', 'emp_id', 'employee', 5);
        const phone_encrypt = encryptPhone(phone);
        const phone_hash = cryptoHelper.hash(phone);
        let sql = `INSERT INTO employee (emp_id, emp_name, gender, dept_id, position_id, hire_date, phone, status, notes, phone_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
        let params = [emp_id, emp_name, gender, dept_id, position_id, hire_date, phone_encrypt, status, notes, phone_hash];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '添加', '添加员工', '添加员工成功', '成功');
        res.json({
            success: true,
            message: '添加员工成功',
            data: result
        });
    } catch (error) {
        console.error('添加员工失败:', error);
        await logUserOperation(req, '添加', '添加员工', '添加员工失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '添加员工失败',
            error: error.message
        });
    }
});

// 修改员工
router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { emp_id, emp_name, gender, dept_id, position_id, hire_date, phone, status, notes } = req.body;
        const phone_encrypt = encryptPhone(phone);
        const phone_hash = cryptoHelper.hash(phone);
        let sql = `UPDATE employee SET emp_name = ?, gender = ?, dept_id = ?, position_id = ?, hire_date = ?, phone = ?, status = ?, notes = ?, phone_hash = ? WHERE emp_id = ?`;
        let params = [emp_name, gender, dept_id, position_id, hire_date, phone_encrypt, status, notes, phone_hash, emp_id];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '更新', '更新员工', '更新员工成功', '成功');
        res.json({
            success: true,
            message: '修改员工成功',
            data: result
        });
    } catch (error) {
        console.error('修改员工失败:', error);
        await logUserOperation(req, '更新', '更新员工', '更新员工失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '修改员工失败',
            error: error.message
        });
    }
});

// 获取修改初始化
router.get('/getUpdateInit', authenticateToken, async (req, res) => {
    try {
        const { emp_id } = req.query;
        const [result] = await db.execute('SELECT * FROM employee WHERE emp_id = ?', [emp_id]);
        result.forEach(item => {
            item.phone = decryptPhone(item.phone);
        });
        res.json({
            success: true,
            message: '获取修改初始化成功',
            data: result
        });
        await logUserOperation(req, '查询', '获取修改初始化', '获取修改初始化成功', '成功');
    } catch (error) {
        console.error('获取修改初始化失败:', error);
        res.status(500).json({
            success: false,
            message: '获取修改初始化失败',
            error: error.message
        });
    }
});

// 删除员工
router.delete('/delete', authenticateToken, async (req, res) => {
    try {
        const { emp_id } = req.query;

        // 验证参数
        if (!emp_id) {
            return res.status(400).json({
                success: false,
                message: '员工ID不能为空'
            });
        }

        // 检查员工是否存在
        const [checkResult] = await db.execute('SELECT emp_id, emp_name FROM employee WHERE emp_id = ?', [emp_id]);
        if (checkResult.length === 0) {
            return res.status(404).json({
                success: false,
                message: '员工不存在'
            });
        }

        // 检查员工是否有关联的预约记录
        const [appointmentCheck] = await db.execute('SELECT COUNT(*) as count FROM appointment WHERE emp_id = ?', [emp_id]);
        if (appointmentCheck[0].count > 0) {
            return res.status(400).json({
                success: false,
                message: `员工"${checkResult[0].emp_name}"还有${appointmentCheck[0].count}条预约记录，无法删除。请先处理相关预约记录。`,
                data: {
                    emp_name: checkResult[0].emp_name,
                    appointment_count: appointmentCheck[0].count
                }
            });
        }

        // 执行删除操作
        let sql = `DELETE FROM employee WHERE emp_id = ?`;
        let params = [emp_id];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '删除', '删除员工', '删除员工成功', '成功');
        if (result.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                message: '删除失败，员工不存在'
            });
        }

        res.json({
            success: true,
            message: '删除员工成功',
            data: result
        });
    } catch (error) {
        if (error.code === 'ER_ROW_IS_REFERENCED_2' || error.message.includes('ER_ROW_IS_REFERENCED')) {
            return res.status(400).json({
                success: false,
                message: '该员工还有关联数据，无法删除。请先移除相关关联记录。',
                error: error.message
            });
        }
        console.error('删除员工失败:', error);
        await logUserOperation(req, '删除', '删除员工', '删除员工失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '删除员工失败',
            error: error.message
        });
    }
});

module.exports = router;